package test.baojia.act.operation;

import com.alibaba.fastjson.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;

import java.util.List;
import java.util.Properties;

/**
 * Bootstrap select控件操作。
 */
public class BsSelectOperation extends WriteOperation {

    private final static String NOT_FOUND_MESSAGE = "Option %s not found in %s";

    private final static String CSS_SELECTOR_BUTTON_TEMPLATE = "#%s +button";

    private final static String CSS_SELECTOR_SPAN_TEMPLATE = "+div > div > ul > li:nth-child(%s) > a > span";

    public void run(JSONObject context, WebDriver driver, Properties resource, JSONObject parentContext) throws Exception{
        super.run(context , driver , resource, parentContext);

        final String id = (String) context.get(OPERATION.byExp.toString());
        final String targetValue = (String) context.get(OPERATION.byValue.toString());

        //令待选项显示，否则选项提示无法交互。
        String buttonCssSelector = String.format(CSS_SELECTOR_BUTTON_TEMPLATE , id);
        driver.findElement(By.cssSelector(buttonCssSelector)).click();

        Select select = this.makeSelectWebElement(true);
        List<WebElement> optionWEs = select.getOptions();
        // CSS SELECTOR语法的序号从1开始。
        int i = 1;
        boolean found = false;
        for(WebElement optionWE : optionWEs){
            if(!isOptionHide(optionWE)){
                if(targetValue.equals(optionWE.getAttribute("value"))){
                    found = true;
                    break;
                }
                i++;
            }
        }

        Assert.assertTrue(found , String.format(NOT_FOUND_MESSAGE , targetValue , id));

        final String cssSelector4Span = String.format(buttonCssSelector + " " + CSS_SELECTOR_SPAN_TEMPLATE , i);
        driver.findElement(By.cssSelector(cssSelector4Span)).click();

    }

    public final static boolean isOptionHide(WebElement option){
        return "true".equals(option.getAttribute("hidden"));
    }
}
